package actions;

import java.sql.SQLException;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.RowSet;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import db.DbException;
import forms.StudentForm;
import model.CountriesModel;
import model.UserModel;

public class StudentCitizenAction extends Action {

	private static final boolean DEBUG = true;
	//private static final int UNKNOWN = -1;
	
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws DbException {
	
		// get student citizen from form
		StudentForm sform = (StudentForm)form;
		String citizen = sform.getCitizen();
		
		if (DEBUG) {
			System.err.println("StudentCitizenAction: saving citizen(" + citizen +")");
		}
		
		// save student citizen into session
		request.getSession().setAttribute("citizen", citizen);
		
		// store StudentForm into session
		sform = (StudentForm)request.getSession().getAttribute("sform");
		
		sform.setCitizen(citizen);
		
		// put list of universities into a vector
		RowSet rset = CountriesModel.getUniversities();

		Vector<String> countries_1 = new Vector<String>();
		Vector<String> countries_2 = new Vector<String>();
		Vector<String> countries_3 = new Vector<String>();

		int count = 0;
		
		try {
			while (rset.next()) {
				
				count = (count + 1)%3;
				
				switch(count) {
					case 1:
						countries_1.add(rset.getString("country_name"));
						break;
					case 2:
						countries_2.add(rset.getString("country_name"));
						break;
					default:
						countries_3.add(rset.getString("country_name"));
						break;
				}
			}
			
			if (countries_2.size() < countries_1.size()) {
				countries_2.add("");
			}
			
			if (countries_3.size() < countries_1.size()) {
				countries_3.add("");
			}
		} catch (SQLException e) {
			System.err.println("SQLException: " + e.getMessage());
		}
		
		request.setAttribute("countries_1", countries_1);
		request.setAttribute("countries_2", countries_2);
		request.setAttribute("countries_3", countries_3);
		
		return mapping.findForward("success");
	}
	
}
